import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "about_orm.settings")
import django

django.setup()

from app01 import models

# 基于对象的查询
# 正向查询
book_obj = models.Book.objects.get(pk=1)
# print(book_obj.pub)     # 关联的对象
# print(book_obj.pub_id)  # 关联的对象id
# print(book_obj.pub.name)

# 反向查询
pub_obj = models.Publisher.objects.get(pk=1)
# print(pub_obj.name)

# 不指定 related_name  类名小写_set
# print(pub_obj.book_set)   # 关系管理对象
# print(pub_obj.book_set.all())   # 所关联的所有的对象

# 指定 related_name = 'books'    books
# print(pub_obj.books)
# print(pub_obj.books.all())


# 基于字段的查询

ret = models.Book.objects.filter(pub__name='沙河出版社')  # __ 跨表

# 不指定related_name  使用  类名小写__
# ret = models.Publisher.objects.filter(book__title='秃头很强')

# 指定related_name = 'books'  使用books
# ret = models.Publisher.objects.filter(books__title='秃头很强')

# 指定related_query_name='book' 使用book
# ret = models.Publisher.objects.filter(book__title='秃头很强')
# print(ret)


# 外键 关系管理对象
# pub_obj.books.set(models.Book.objects.filter(pk__in=[2,4,6]))  # [对象,]
# pub_obj.books.add(*models.Book.objects.filter(pk__in=[2,4,6]))  # 对象,
# 使用remove  clear ，必须外键字段可以为空 null=True
# pub_obj.books.remove(*models.Book.objects.filter(pk__in=[2,4,6]))  # 对象,

# pub_obj.books.clear()

# pub_obj.books.create(title='红浪漫续集')